package com.handu.luna.core.domain.promotion;

import com.handu.luna.core.domain.search.BonusPromotionSearch;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.Entity;
import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.handu.luna.core.domain.promotion.BonusPromotion.GrantType.USER;

/**
 * Created by wangzailiang on 2014/7/2.
 */

@Entity
public class CashCardPromotion extends BonusPromotion {


    public static Specification<CashCardPromotion> selectCondition(BonusPromotionSearch bonusPromotionSearch) {
		return new Specification<CashCardPromotion>() {
			@Override
			public Predicate toPredicate(Root<CashCardPromotion> root,
					CriteriaQuery<?> query, CriteriaBuilder builder) {

				Predicate predicate = builder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();

				if (StringUtils.isNotBlank(bonusPromotionSearch.getName())) {
					expressions.add(builder.like(root.<String> get("name"),"%"+ bonusPromotionSearch.getName() +"%"));
				}

                if(null != bonusPromotionSearch.getGrantType() &&!"0".equals(bonusPromotionSearch.getGrantType())) {
                    int grantTypeIndex = -1;
                    switch (bonusPromotionSearch.getGrantType()) {
                        case "USER":
                            grantTypeIndex = 0;
                            break;
                        case "GOOD":
                            grantTypeIndex = 1;
                            break;
                        case "UNDERLINE":
                            grantTypeIndex = 3;
                            break;
                        default:
                    }
                    expressions.add(builder.equal(root.<Integer>get("grantType"), grantTypeIndex));
                }

                if (StringUtils.isNotBlank(bonusPromotionSearch.getMinPrice())) {
					//expressions.add(builder.greaterThanOrEqualTo(root.<String>get("bonusPrice"), cashCardPromotionSearch.getMinPrice()));
                    expressions.add(builder.equal(root.<String>get("bonusPrice"), bonusPromotionSearch.getMinPrice()));
				}

               /* if (StringUtils.isNotBlank(cashCardPromotionSearch.getMaxPrice())) {
					expressions.add(builder.lessThanOrEqualTo(root.<String>get("bonusPrice"), cashCardPromotionSearch.getMaxPrice()));
				}*/

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date1 = null;
				Date date2 = null;

				if(StringUtils.isNotBlank(bonusPromotionSearch.getStartDate())){
					try {
						date1 = sdf.parse(bonusPromotionSearch.getStartDate());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					expressions.add(builder.greaterThanOrEqualTo(root.<Date>get("useStartDate"), date1));
				}

				if(StringUtils.isNotBlank(bonusPromotionSearch.getEndDate())){
					try {
						date2 = sdf.parse(bonusPromotionSearch.getEndDate());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					expressions.add(builder.lessThanOrEqualTo(root.<Date>get("useStartDate"), date2));
				}

                if(StringUtils.isNotBlank(bonusPromotionSearch.getStatus())) {
                   if(bonusPromotionSearch.getStatus().equals(PromotionStatus.UNACTIVATED.description)) {
                       expressions.add(builder.greaterThan(root.<Date>get("useStartDate"), new Date()));
                   }else if(bonusPromotionSearch.getStatus().equals(PromotionStatus.ACTIVATING.description)) {
                       expressions.add(builder.lessThan(root.<Date>get("useStartDate"), new Date()));
                       expressions.add(builder.greaterThan(root.<Date>get("useEndDate"), new Date()));
                   }else if(bonusPromotionSearch.getStatus().equals(PromotionStatus.ACTIVATED.description)){
                       expressions.add(builder.lessThan(root.<Date>get("useEndDate"), new Date()));
                   }
                }

				return query.where(predicate).getRestriction();

			}
		};
	}

    public static GrantType[] grantTypeValues() {
        return new GrantType[]{USER,GrantType.UNDERLINE,GrantType.GOOD};
    }

    public CashCardPromotion(){
        this.limitPrice = BigDecimal.valueOf(0);
    }

    public CashCardPromotion(String name, GrantType grantType, String useRanges, BigDecimal bonusPrice, BigDecimal limitPrice, Date grantStartDate, Date grantEndDate, Date useStartDate, Date useEndDate, String brandIds, String remark) {
        super(name, grantType, useRanges, bonusPrice, limitPrice, grantStartDate, grantEndDate, useStartDate, useEndDate, brandIds, remark);
    }

    /**
     * 修改发放数量
     */
    public void updateGrantNum(Long bonusPromotionId, Long grantNum) {
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(bonusPromotionId);
        context.getCashCardPromotionRepository().updateGrantNum(cashCardPromotion.getGrantNum() + grantNum,bonusPromotionId);
    }

    /**
     * 修改使用数量
     */
    public void updateUsedNum(Long bonusPromotionId, Long usedNum) {
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(bonusPromotionId);
        context.getCouponPromotionRepository().updateUsedNum(cashCardPromotion.getGrantNum() + usedNum,bonusPromotionId);
    }


    /**
     * 查询全部现金卡类型(分页)
     * @param pageable
     * @return
     */
    public Page<CashCardPromotion> findAll(Specification<CashCardPromotion> specification,Pageable pageable) {

        Page<CashCardPromotion> page;
        if(null == specification) {
            page = context.getCashCardPromotionRepository().findAll(pageable);
        }else {
            page = context.getCashCardPromotionRepository().findAll(specification,pageable);
        }

        List<CashCardPromotion> list = page.getContent();

        for(CashCardPromotion cashCardPromotion : list) {
            fromDateBaseToView(cashCardPromotion);
        }

        return page;
    }
    /**
     * 保存现金卡类型
     * @param cashCardPromotion
     * @return
     */
    public CashCardPromotion save(CashCardPromotion cashCardPromotion) {

        fromViewToDateBase(cashCardPromotion);
        return context.getCashCardPromotionRepository().save(cashCardPromotion);

    }

    /**
     * 查询现金卡类型
     * @param id
     * @return
     */
    public CashCardPromotion findOne(Long id) {

        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(id);
        fromDateBaseToView(cashCardPromotion);
        return cashCardPromotion;
    }







}
